
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { HTTP } from '@ionic-native/http';
import { NativeService } from './NativeService';

@Injectable()
export class HttpService {
  baseUrl:string = "http://106.14.33.61:8081";
  // baseUrl:string = "http://192.168.10.177";
  // baseUrl:string = "https://api.ok5007.com/";
  imageUrl:string = "https://img.56596.club/";

  constructor(public http: HttpClient,
              public native:NativeService,
              public nativeHttp:HTTP) {

  }

  public post(url: string, params: any = null, callback) {
    if (this.native.isMobile()){
      this.nativeHttp.post(url,params,{}).then(res=>{
        let obj = JSON.parse(res.data);
        if(obj.StatusCode){
          this.native.showToast(obj.Message);
          callback(null,obj.Message);
        }else {
          callback(obj,null);
        }
      }).catch( err =>{
        this.native.hideLoading();
        callback(null,err);
      });
    }else {
      let authtoken = localStorage.getItem('authtoken');
      let options = {
        headers:{}
      };
      if (authtoken){
        options.headers = {authtoken:authtoken}
      }
      this.http.post(url, params, options).subscribe((res: any) => {
        if(res.StatusCode){
          this.native.showToast(res.Message);
          callback(null,res.Message);
        }else {
          callback(res,null);
        }
      }, err => {
        callback(null,err);
      });
    }
  }
  // get数据
  public get(url: string, params: any,callback) {
    url = this.setGetUrl(url,params);
    if (this.native.isMobile()){
      this.nativeHttp.get(url,{},{}).then(res=>{
        let obj = JSON.parse(res.data);
        if(obj.StatusCode){
          this.native.showToast(obj.Message);
          callback(null,obj.Message);
        }else {
          callback(obj,null);
        }
      }).catch( err =>{
        callback(null,err);
      });
    }else {
      let options = {headers:{}};
      let authtoken = localStorage.getItem('authtoken');
      if (authtoken){
        options.headers = {authtoken:authtoken}
      }
      this.http.get(url,options).subscribe( (res:any) => {
        if(res.StatusCode){
          this.native.showToast(res.Message);
          callback(null,res.Message);
        }else {
          callback(res,null);
        }
      },err=>{
        this.native.hideLoading();
        callback(null,err);
      });
    }
  }
  private setGetUrl(url,parmas:any):string{
    var u = this.baseUrl + url;
    var par = '?';
    for (let key in parmas){
      par += key+"="+parmas[key]+"&";
    }
    u = u + par.substring(0,par.length - 1);
    return u;
  }

}
